import { ifKeepKeyUnit, Tables } from "./base";
import { MongodbMoudle } from "mx-database";
let tinify = require("tinify");

export interface ifAppkeys {
    // (...args: any[]): this;
    init(...args: string[]): Promise<boolean>;
    getPressKey(): Promise<ifKeepKeyUnit>;
}
export class AppKeys implements ifAppkeys {
    keyCount: { [x: string]: number } = {};
    constructor() {
        
    }
    async init(...keys: string[]) {
        // 这里先检查一下所有key的额度
        // 这里生成一个临时的执行文件
        for (let i = 0; i < keys.length; i++) {
            this.keyCount[keys[i]] = await this.queryCount(keys[i]);
        }

        return true;
    }

    private queryCount(key: string) {
        tinify.key = key;
        return new Promise<number>(function (reslove) {
            tinify.validate(function (err) {
                if (err) reslove(500);
                // Validation of API key failed.
                reslove(500 - (tinify.compressionCount || 0))
            })
        })
    }

    private update(key: string, count: number) {
        this.keyCount[key] = count;
    }

    async getPressKey(): Promise<ifKeepKeyUnit> {
        for (let key in this.keyCount) {
            if (this.keyCount[key] > 0) {
                return { key: key, count: this.keyCount[key], change: this.update.bind(this, key), database: "" }
            }
        }

        return undefined;
    }
}

export class MongoApps implements ifAppkeys {
    databaseName = "";

    constructor(databaseName:string) {
        this.databaseName = databaseName;
    }

    async init(...keys: string[]) {
        // 这里先检查一下所有key的额度
        // 这里生成一个临时的执行文件
        return true;
    }
    async change(this: ifKeepKeyUnit, nCount: number) {
        this.count = nCount;
        let db = await MongodbMoudle.get_database(this.database).get_unit(Tables.user, { key: this.key }).load()
        db.set('count', nCount);
        return db.force_save();
    }

    async getPressKey() {
        let db = await MongodbMoudle.get_database(this.databaseName).get_unit(Tables.user, { 'count': { '$gt': 0 } }).load()
        return { count: db.get('count') as number, key: db.get('key') as string, change: this.change, database: this.databaseName }
    }
}